package cn.cvs.web;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SupplierService;
import cn.cvs.util.Constants;
import cn.cvs.util.DataTransfer;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class SupplierController {
    @Resource
    SupplierService supplierService;

    @RequestMapping("/sys/supplier/list")
    public String list(@RequestParam(value = "querySupCode",required = false) String querySupCode, @RequestParam(value = "querySupName",required = false) String querySupName,@RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageNo, Model model){
        //querySupCode
        model.addAttribute("querySupCode",querySupCode);
        //querySupName
        model.addAttribute("querySupName",querySupName);
        //supplierList
        List<Supplier> suppliers = supplierService.querySupplies(querySupCode, querySupName, pageNo, Constants.pageSize);
        model.addAttribute("supplierList",suppliers);
        //totalCount
        //currentPageNo
        //totalPageCount
        //totalCount (参与条件分页)总记录数
        int count = supplierService.queryCount(querySupCode,querySupName);
        model.addAttribute("totalCount",count);
        //currentPageNo 当前页码 就是入参 pageIndex
        model.addAttribute("currentPageNo",pageNo);
        //totalPageCount 总页数
        PageSupport pageSupport = new PageSupport();
        //设置pageSize 一页几条记录
        pageSupport.setPageSize(Constants.pageSize);
        //设置参与分页的总记录数
        pageSupport.setTotalCount(count);
        //获得总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "supplier/list";
    }
    @RequestMapping("/sys/supplier/toAdd")
    public String toAddSupplier(Model model){
        return "supplier/add";
    }

    @PostMapping("/sys/supplier/add")
    public String addSupplier(Supplier supplier, HttpSession session, HttpServletRequest request,
                              Model model, @RequestParam(value = "attaches",required = false) MultipartFile[] attaches){
        SysUser attribute = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            model.addAttribute("error","请登录后操作");
            return "redirect:/sys/supplier/list";
        }
        for (int i=0;i<attaches.length;i++){
            String saveFileName=System.currentTimeMillis()+"_"+attaches[i].getOriginalFilename();
            String realPath=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");
            File file = new File(realPath);
            if (!file.exists()){
                file.mkdirs();
            }
            File saveFile = new File(file, saveFileName);
            try {
                attaches[i].transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("图片保存失败"+e);
            }
            String path=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
            if (i==0){
                supplier.setCompanyLicPic(path);
            }else{
                supplier.setOrgCodePic(path);
            }
        }
        supplier.setCreatedTime(new Date());
        supplier.setCreatedUserId(attribute.getId());
        int i = supplierService.addSupplier(supplier);
        if (i>0){
            return "redirect:/sys/supplier/list";
        }else {
            throw new RuntimeException("添加供货商失败，请重试");
        }
    }
    @GetMapping("/sys/supplier/toUpdate/{dd}")
    public String toUpdateSupplier(@PathVariable("dd") Integer id, Model model){
        Supplier supplier = supplierService.queryById(id);
        System.out.println(supplier);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }
    @RequestMapping("/supplier/update")
    public String updateSupplier(Supplier supplier,HttpSession session,Model model){
        SysUser attribute = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            model.addAttribute("error","请登录后操作");
            return "redirect:/sys/supplier/list";
        }
        supplier.setUpdatedTime(new Date());
        supplier.setUpdatedUserId(attribute.getId());
        int i = supplierService.update(supplier);
        if (i>0){
            return "redirect:/sys/supplier/list";
        }else{
            throw new RuntimeException("修改失败，请重试");
        }
    }
    @RequestMapping("/sys/supplier/view/{id}")
    public String viewSupplier(@PathVariable("id") Integer id,Model model){
        Supplier supplier = supplierService.queryById(id);
        model.addAttribute("supplier",supplier);
        return "supplier/view";
    }

    @ResponseBody
    @GetMapping("/sys/supplier/{suid}/view")
    public Object asyViewSupplier(@PathVariable("suid") Integer id){
        DataTransfer<Supplier> dto=new DataTransfer<>();
        try {
            Supplier supplier = supplierService.queryById(id);
            if (supplier==null){
                dto.setStatus("nodata");
                return JSON.toJSONString(dto);
            }
            dto.setStatus("ok");
            dto.setData(supplier);
            return JSON.toJSONString(dto);
        } catch (Exception e) {
            e.printStackTrace();
            dto.setStatus("failed");
            return JSON.toJSONString(dto);
        }
    }
}
